package com.taotao.wechat;

import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.RopAppSecret;
import com.taotao.rop.database.mapper.RopAppSecretMapper;
import com.taotao.wechat.business.Request;
import com.taotao.wechat.business.TextRecognition;
import com.taotao.wechat.business.User;
import com.taotao.wechat.message.MessageEntry;
import com.taotao.wechat.message.resp.BaseMessage;
import com.taotao.wechat.message.resp.TextMessage;
import com.taotao.wechat.util.MessageUtil;
import com.taotao.wechat.util.WebServiceUtil;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 核心服务类
 */
public class CoreService {
    private static Logger logger = Logger.getLogger(CoreService.class);

    /**
     * 处理微信发来的请求
     *
     * @param request 微信发来的请求
     * @param appKey 微信公众平台开发者ID
     * @return 处理结果
     */
    public static String processRequest(HttpServletRequest request, String appKey, RopAppSecretMapper appSecretMapper) {
        String respMessage = "";
        BaseMessage baseMessage = new BaseMessage();
        try {
            //取得接收到消息的公共属性
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            String toUserName = requestMap.get(MessageEntry.ToUserName);
            String fromUserName = requestMap.get(MessageEntry.FromUserName);
            Long createTime = Long.valueOf(requestMap.get(MessageEntry.CreateTime));
            String msgType = requestMap.get(MessageEntry.MsgType);
            String msgId = requestMap.get(MessageEntry.MsgId);
            logger.debug("appKey：" + appKey + " - from: " + fromUserName + " - to: " + toUserName);

            // 回复消息
            baseMessage.setToUserName(fromUserName);
            baseMessage.setFromUserName(toUserName);
            baseMessage.setCreateTime(new Date().getTime());
            baseMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

            //检查是否是接入的微信appId
            RopAppSecret condition = new RopAppSecret();
            condition.setAppId(appKey);
            condition.setStatus(Constant.STATUS_ENABLE);
            List<RopAppSecret> ropAppSecretList = appSecretMapper.getList(condition);
            if (ropAppSecretList == null || ropAppSecretList.size() < 1) {
                TextMessage textMessage = new TextMessage(baseMessage);
                textMessage.setContent("亲，您尚未接入平台，请联系管理员");
                return MessageUtil.textMessageToXml(textMessage);
            }

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
                String content = requestMap.get(MessageEntry.Content);
                respMessage = TextRecognition.textRecognition(baseMessage, content, appKey);
            }
            // 图片消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
                baseMessage.setMsgType(msgType);
                String picUrl = requestMap.get(MessageEntry.PicUrl);
                respMessage = TextRecognition.textRecognition(baseMessage, picUrl, appKey);
            }
            // 地理位置消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
                respMessage = TextRecognition.getRespByLocation(baseMessage, requestMap);
            }
            // 链接消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
                //TODO: 您发送的是链接消息！;
            }
            // 音频消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
                String recognition = requestMap.get(MessageEntry.RECOGNITION);
                if (recognition != null && recognition.length() > 0) {
                    respMessage = TextRecognition.textRecognition(baseMessage, recognition, appKey, MessageUtil.REQ_MESSAGE_TYPE_VOICE);
                } else {
                    TextMessage textMessage = new TextMessage(baseMessage);
                    textMessage.setContent("亲~ 语音无法识别，请输入文本吧~~");
                    respMessage = MessageUtil.textMessageToXml(textMessage);
                }
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get(MessageEntry.Event);
                // 订阅
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    respMessage = TextRecognition.textRecognition(baseMessage, "welcome", appKey);
                    try {
                        //插入wechatUser表
                        new User().insertUser(appKey, fromUserName);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }
                }
                // 取消订阅
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
                    //在wechatUser表中删除此用户
                    new User().deleteUser(appKey, fromUserName);
                }
                // 自定义菜单点击事件--click button
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    // TODO 自定义菜单
                    String eventKey = requestMap.get("EventKey");
                    //查询翻牌活动得奖记录，临时的
                    if (eventKey.equals("9998")) {
                        TextMessage textMessage = new TextMessage(baseMessage);
                        textMessage.setContent(WebServiceUtil.getData(fromUserName));
                        respMessage = MessageUtil.textMessageToXml(textMessage);
                    } else {
                        respMessage = TextRecognition.textRecognition(baseMessage, eventKey, appKey);
                    }
                } else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION_SELECT)) {
                    respMessage = TextRecognition.getRespByLocation(baseMessage, requestMap);
                }
            }
            try {
                Request.insertRequest(appKey, fromUserName, requestMap, respMessage);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            TextMessage textMessage = new TextMessage(baseMessage);
            textMessage.setContent("请求处理异常，请稍候尝试！");
            respMessage = MessageUtil.textMessageToXml(textMessage);
        }
        return respMessage;
    }
}
